package com.mywork.mvpkodeinxml.rx

import com.mywork.mvpkodeinxml.common.getXmlObj
import com.mywork.mvpkodeinxml.model.response.BaseEntity
import com.mywork.mvpkodeinxml.model.response.CommonResp
import io.reactivex.Observable
import io.reactivex.functions.Function

/*
* 把CommonResp解析成T:BaseEntity
* 并处理BaseEntity中的错误信息
* */
class BaseCommonFunc<T : BaseEntity>(val entityClass: Class<*>) : Function<CommonResp, Observable<T>> {
    override fun apply(t: CommonResp): Observable<T> {
        val result = t.body?.commonFuncResponse?.commonFuncResult ?: return Observable.error(BaseException(-1, "服务端返回无数据!"))
        val data = result.getXmlObj<T>(entityClass)
        if (data == null) {
            return Observable.error(BaseException(-1, "服务端返回数据解析异常!"))
        } else if (!data.code.equals("0")) {
            return Observable.error(BaseException(-1, data.msg))
        }
        return Observable.just(data)
    }
}